package cn.donting.jme.swing;

import com.formdev.flatlaf.extras.components.FlatTabbedPane;
import lombok.extern.slf4j.Slf4j;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import java.awt.*;

/**
 * @see Tab
 */

@Slf4j
public class JDTabbedPane extends FlatTabbedPane {

    private Component activeTab;

    public JDTabbedPane() {
        setTabCloseCallback(this::closeEvent);
        addChangeListener(this::activeTab);
    }

    /**
     * 一个 Tab 激活
     * @param changeEvent
     */
    private void activeTab(ChangeEvent changeEvent){
        Component selectedComponent = getSelectedComponent();
        if (activeTab!=null && activeTab instanceof Tab) {
            ((Tab) activeTab).activateChange(false);
        }
        if (selectedComponent instanceof Tab) {
            ((Tab) selectedComponent).activateChange(true);
        }
        activeTab=selectedComponent;
    }


    /**
     * 一个 tab 关闭
     * @param jTabbedPane
     * @param index
     */
    private void closeEvent(JTabbedPane jTabbedPane, Integer index) {
        Component componentAt = jTabbedPane.getComponentAt(index);
        if (componentAt instanceof Tab) {
            ((Tab) componentAt).close();
        }
        jTabbedPane.remove(index);
    }


}
